import React, { Component } from 'react';
import ImageLoader from '../../component/imageLoader';
import PropTypes from 'prop-types';
import './index.css';
// import { connect } from "dva";

const doc = document;
const win = window;

const getStyle = (ele, name) => {
    return win.getComputedStyle ? win.getComputedStyle(ele, name || null) : ele.currentStyle;
}
const isCanvas = !!doc.createElement('canvas').getContext;

class Signer extends Component {
    constructor(props){
        super(props);
        this.state = {
            isLoading: false,
            img: props.img || null,
            width: '100%',
            height: '100%',
            background: props.background || '#fff',
            lineStyle: {
                width: props.lineStyle ? props.lineStyle.size : 1,
                color: props.lineStyle ? props.lineStyle.color : '#000'
            },
            isFooter: true
        };

        this.start = this.start.bind(this);
        this.move = this.move.bind(this);
        this.end = this.end.bind(this);
        this.clear = this.clear.bind(this);
        this.save = this.save.bind(this);
    }
    componentDidMount() {
        this.lastX = 0;
        this.lastY = 0;
        this.setSize();
        this.setBackground();
        this.drawImage();
    }
    componentWillReceiveProps(nextProp) {
        const { props } = this;

        this.setState({
            isLoading: nextProp.isLoading,
            img: nextProp.img
        }, () => {
            if(props.img !== nextProp.img){
                this.drawImage();
            }
        });

        // if (props.isLoading !== nextProp.isLoading){
        //     this.setState({
        //         isLoading: nextProp.isLoading
        //     })
        // }
        // if (props.img !== nextProp.img) {
        //     this.setState({
        //         img: nextProp.img
        //     }, () => {
        //         this.drawImage();
        //     })
        // }
    }
    getCanvas(){
        if(this._canvas){
            return {
                canvas: this._canvas,
                ctx: this._canvas.getContext('2d')
            }
        }
        return null;
    }
    setSize(w, h){
        const c = this.getCanvas();
        const { isFooter } = this.state;

        if(c){
            const borderX = ((parseInt(getStyle(c.canvas)['border-left-width'])) || 0) + (parseInt(getStyle(c.canvas)['border-right-width'] || 0));
            const borderY = ((parseInt(getStyle(c.canvas)['border-top-width'])) || 0) + (parseInt(getStyle(c.canvas)['border-bottom-width'] || 0));
            const marginX = isFooter ? (parseInt(getStyle(this._footer)['margin-top']) || 0) + (parseInt(getStyle(this._footer)['margin-bottom']) || 0) : 0;

            c.canvas.width = w || (this._el.offsetWidth - borderX);
            c.canvas.height = h || (isFooter ? this._el.offsetHeight - borderY - (this._footer.offsetHeight + marginX) : this._el.offsetHeight - borderY);
        }
    }
    setBackground(){
        const { background } = this.state;
        const c = this.getCanvas();
        if(c) {
            c.ctx.fillStyle = background;
            c.ctx.fillRect(0, 0, c.canvas.width, c.canvas.width);
        }
    }
    setLineStyle(){
        const c = this.getCanvas();
        if(c) {
            const { lineStyle } = this.state;
            c.ctx.strokeStyle = lineStyle.color;
            c.ctx.lineWidth = lineStyle.width;
            c.ctx.lineCap = "round";
            c.ctx.lineJoin = "round";
        }
    }

    draw(x, y, isDown){
        const c = this.getCanvas();
        if(c && isDown){
            c.ctx.beginPath();
            this.setLineStyle();
            c.ctx.moveTo(this.lastX, this.lastY);
            c.ctx.lineTo(x, y);
            c.ctx.closePath();
            c.ctx.stroke();
        }

        this.lastX = x;
        this.lastY = y;
    }
    drawImage(){
        const { img } = this.state;
        const c = this.getCanvas();
        if(c && img){
            c.ctx.drawImage(img, 0, 0);
        }
    }
    clear(){
        const c = this.getCanvas();
        if(c) {
            c.ctx.clearRect(0, 0, c.canvas.width, c.canvas.height);
        }
    }
    save(){
        const c = this.getCanvas();
        const { props } = this;
        if(c) {
            if(props.onSave){
                props.onSave({
                    el: c.canvas,
                    ctx: c.ctx,
                    content: c.canvas.toDataURL()
                });
                return;
            }
            this.saveAsImage();
        }
    }
    saveAsImage(){
        const c = this.getCanvas();
        if(c) {
            const link = doc.createElement("a");
            const imgData = c.canvas.toDataURL({
                format: 'png',
                quality: 1,
                width: c.canvas.width,
                height: c.canvas.height
            });
            const blob = dataURLtoBlob(imgData);
            const url = URL.createObjectURL(blob);
            link.download = `${(new Date).getTime()}.png`;
            link.href = url;
            link.click();
        }
        function  dataURLtoBlob(dataurl: string) {
            let arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = win.atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);

            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type: mime});
        }
    }
    start(e){
        const { canvas } = this.getCanvas();
        e.preventDefault();
        this.isMousePressed = true;
        this.draw(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop, false);
    }
    move(e){
        if(this.isMousePressed) {
            e.preventDefault();
            const { canvas } = this.getCanvas();
            this.draw(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop, true);
        }
    }
    end(e){
        e.preventDefault();
        delete this.isMousePressed;
    }
    render(){
        const { isFooter, isLoading } = this.state;
        const c = this.getCanvas();

        let render;
        if(isLoading && c) {
            render = <div style={{
                position: "absolute",
                width: c.canvas.offsetWidth,
                height: c.canvas.offsetHeight
            }}>加载图片ing..</div>
        }

        return (
            <div className="signer-canvas" ref={(el) => {
                this._el = el;
            }}>
                {isCanvas ? (
                    <React.Fragment>
                        {render}
                        <canvas ref={(el) => {
                            this._canvas = el;
                        }}
                            onMouseDown={this.start}
                            onMouseMove={this.move}
                            onMouseUp={this.end}
                        ></canvas>
                    </React.Fragment>
                ) : (
                    <div>当前浏览器暂不支持此功能</div>
                )}
                {isFooter && (
                    <div ref={(el) => {
                        this._footer = el;
                    }} className="footer">
                        <button onClick={this.clear}>清除</button>
                        <button onClick={this.save}>保存</button>
                    </div>
                )}
            </div>
        );
    }
}

Signer.propTypes = {
    lineStyle: PropTypes.object,
    isLoading: PropTypes.bool,
    background: PropTypes.string,
    isFooter: PropTypes.bool,
    img: PropTypes.object
};
Signer.defaultProps = {
    lineStyle: null,
    isLoading: null,
    background: null,
    isFooter: null,
    img: null
};

const Wrapping = ImageLoader(Signer);

class Container extends Component {
    constructor(props){
        super(props);
    }
    render(){
        return (
            <div className="signer-container">

                <Wrapping src="https://files.jb51.net/file_images/article/201803/201832890926258.jpg?20182289938" />

            </div>
        );
    }
}


export default Container;